package com.foreknow.test;
/**
 * 使用的库为json-lib
 * 作用：
 * 1.可以讲bean转换为字符串
 * 2.可以将字符串转换为bean
 */

import com.foreknow.model.Admin;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JSONArrayDemo {
    public static void main(String[] args) {
        JSONArray jsonArray =new JSONArray();
        jsonArray.add(0,"tom1");
        jsonArray.add(1,"tom2");
        jsonArray.add(2,"tom3");
        jsonArray.element("test.123");
        System.out.println(jsonArray);
        System.out.println(jsonArray.get(0));
        System.out.println("-----------------------");

        //JSONObject ：JSON字符串对象形式
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("username","tom123");
        jsonObject.put("password","11111");
        jsonArray.add(jsonObject);
        System.out.println(jsonArray);

        //可以使用json-lib库将list集合转换为json串
        Admin admin =new Admin();
        admin.setId(1);
        admin.setUsername("tom");
        admin.setPassword("123");

        Admin admin1 =new Admin();
        admin.setId(2);
        admin.setUsername("tom2");
        admin.setPassword("222");

        List<Admin> list = new ArrayList<>();
        list.add(admin);
        list.add(admin1);

        JSONArray json = JSONArray.fromObject(list);
        System.out.println(json.toString());

        System.out.println("--------------------------");

        Map<String,Object>map = new HashMap<>();
        map.put("1",admin);
        map.put("2",admin1);
        JSONObject jsonObject1 = JSONObject.fromObject(map);
        System.out.println(jsonObject1.toString());
    }
}
